# -*-coding:utf-8-*-
import fake_useragent
import requests
import random
import time

ua = fake_useragent.UserAgent()


def get_fujian(file_id, filename, cookie):
    headers = {
        'User-Agent': f'{ua.random}'
    }
    while 1:
        try:
            response = requests.get('https://api.zsxq.com/v2/files/%s/download_url' % file_id, cookies=cookie, headers=headers)
            file_url = response.json()['resp_data']['download_url']
            break
        except Exception as e:
            print("获取附件url重试!!!")
            time.sleep(random.randint(1, 3))
    retry_time = 1
    while 1:
        try:
            res = requests.get(file_url, headers=headers, verify=False, timeout=30)
            with open(filename, 'wb') as f1:
                f1.write(res.content)
            break
        except Exception as e:
            print(e)
            print("附件请求重试...")
            retry_time += 1
            time.sleep(random.randint(1, 3))

# 获取图片
def get_images(img_url, image_name):
    headers = {
        'User-Agent': f'{ua.random}'
    }
    retry_time = 1
    while 1:
        try:
            res = requests.get(img_url, headers=headers, verify=False)
            with open(image_name, 'wb') as f1:
                f1.write(res.content)
            break
        except Exception as e:
            print(e)
            print("img请求重试...")
            retry_time += 1
            time.sleep(random.randint(1, 3))
        if retry_time > 3:
            print("图片下载失败...url:%s" % img_url)
            break
def get_headimage(head_url, user_id):
    headers = {
        'User-Agent': f'{ua.random}'
    }
    retry_time = 1
    while 1:
        try:
            res = requests.get(head_url, headers=headers, verify=False)
            with open(user_id, 'wb') as f1:
                f1.write(res.content)
            break
        except Exception as e:
            print(e)
            print("img请求重试...")
            retry_time += 1
            time.sleep(random.randint(1, 3))
        if retry_time > 3:
            print("图片下载失败...url:%s" % head_url)
            break

if __name__ == '__main__':
    pass
    # cookies = {
    #     'zsxq_access_token': '3A012422-8484-1FB6-1319-F690F2AD437B_65ACF3083DB9A75D',
    #     'abtest_env': 'product',
    #     'zsxqsessionid': '43bde3cc6426439b1c95da05371f85ce',
    # }
    # data = get_fujian("815551858448542", 'E:\work\AIGC时代的多模态知识工程思考与展望.pdf', cookies)
    # print(data)
